// Editor: myBigPro9/src/views/teacher/ImageQuestionSearch.vue
// Action: Create
<template>
  <el-card class="image-search-container">
    <template #header>
      <div class="card-header">
        <el-icon><CameraFilled /></el-icon>
        <span>AI 拍照搜题</span>
      </div>
    </template>

    <div v-if="!result.answer" class="upload-section">
      <el-upload
        ref="uploadRef"
        drag
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleFileChange"
        accept="image/*"
        class="image-uploader"
      >
        <div v-if="!imageUrl" class="upload-prompt">
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将图片拖到此处，或<em>点击上传</em>
          </div>
        </div>
        <div v-else class="image-preview">
            <img :src="imageUrl" alt="Preview" />
            <div class="preview-actions">
                <el-button type="primary" :icon="Search" @click.stop="handleSearch" :loading="isLoading" circle />
                <el-button type="danger" :icon="Delete" @click.stop="handleRemove" circle />
            </div>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传包含清晰题目的图片 (jpg/png/jpeg)
          </div>
        </template>
      </el-upload>
      <div v-if="isLoading" class="loading-status">
        <el-progress
            :text-inside="true"
            :stroke-width="20"
            :percentage="uploadProgress"
            style="margin-bottom: 10px;"
        />
        <p>{{ loadingText }}</p>
      </div>
    </div>

    <div v-else class="result-section">
      <el-page-header @back="resetSearch" class="result-header">
        <template #content>
          <span>智能分析结果</span>
        </template>
      </el-page-header>
      
      <el-row :gutter="20">
        <el-col :span="12">
            <el-card shadow="never">
                <template #header><strong>识别出的问题</strong></template>
                <div class="question-text">{{ result.question }}</div>
            </el-card>
        </el-col>
        <el-col :span="12">
            <el-card shadow="never">
                <template #header><strong>AI 详细解答</strong></template>
                <div class="answer-content" v-html="formattedAnswer"></div>
            </el-card>
        </el-col>
      </el-row>
    </div>

  </el-card>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { UploadFilled, Search, Delete, CameraFilled } from '@element-plus/icons-vue';
import imageQuestionService from '../../services/imageQuestionService';
import MarkdownIt from 'markdown-it';

const uploadRef = ref();
const imageFile = ref(null);
const imageUrl = ref('');
const isLoading = ref(false);
const loadingText = ref('准备就绪');
const uploadProgress = ref(0);
const result = ref({ question: '', answer: '' });

const md = new MarkdownIt();

const formattedAnswer = computed(() => {
    return md.render(result.value.answer || '');
});

const handleFileChange = (file) => {
  const isImage = file.raw.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请上传图片格式文件！');
    return;
  }
  imageFile.value = file;
  imageUrl.value = URL.createObjectURL(file.raw);
};

const handleRemove = () => {
  imageFile.value = null;
  imageUrl.value = '';
  uploadRef.value.clearFiles();
};

const handleSearch = async () => {
    if (!imageFile.value) {
        ElMessage.warning('请先选择一张图片');
        return;
    }
    isLoading.value = true;
    loadingText.value = '正在上传并识别图片...';
    try {
        const data = await imageQuestionService.searchByImage(imageFile.value.raw, (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            uploadProgress.value = percentCompleted;
            if (percentCompleted === 100) {
                 loadingText.value = '图片上传完成，正在进行AI分析，请稍候...';
            }
        });

        if (data.error) {
            throw new Error(data.error);
        }
        
        result.value = data;
        ElMessage.success('分析成功！');

    } catch (error) {
        ElMessage.error('分析失败: ' + error.message);
    } finally {
        isLoading.value = false;
        uploadProgress.value = 0;
    }
};

const resetSearch = () => {
    handleRemove();
    result.value = { question: '', answer: '' };
};

</script>

<style scoped>
.image-search-container {
  min-height: calc(100vh - 140px);
}
.upload-section {
  text-align: center;
  padding: 40px 0;
}
.image-uploader {
  width: 500px;
  margin: 0 auto;
}
.image-uploader :deep(.el-upload-dragger) {
  padding: 0;
  border: 2px dashed #dcdfe6;
  border-radius: 10px;
}
.upload-prompt {
  padding: 40px;
}
.image-preview {
  position: relative;
  width: 100%;
  height: 200px; /* Or adjust as needed */
}
.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
.image-preview:hover .preview-actions {
  opacity: 1;
}
.preview-actions {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  opacity: 0;
  transition: opacity 0.3s;
}
.loading-status {
  margin-top: 20px;
  color: #606266;
}
.result-section {
    animation: fadeInUp 0.5s;
}
.result-header {
    margin-bottom: 20px;
}
.question-text, .answer-content {
    line-height: 1.7;
    white-space: pre-wrap;
    font-size: 15px;
}
.answer-content :deep(p), .answer-content :deep(ol), .answer-content :deep(ul) {
    margin-bottom: 1em;
}
.answer-content :deep(code) {
    background-color: #f4f4f5;
    padding: 2px 4px;
    border-radius: 4px;
    font-family: 'Courier New', Courier, monospace;
}
</style>